﻿using System;
using System.Linq;
using Biz.Buffer;
using Biz.EF.Gateway.Monitor;
using Biz.EF.Platform;
using Hjt212Parser;
using log4net;

namespace Biz.Process
{
    public class DownlineDataInstructionTotal
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(DownlineDataInstructionTotal));
        public static void Gen2011ToGateway()
        {
            try
            {
                using (GatewayMonitorContext gCtx = new GatewayMonitorContext())
                using (PlatformContext pCtx = new PlatformContext())
                {
                    var items =
                        pCtx.RealDataMains.Where(t => t.是否下发 == null || t.是否下发 == false)
                            .OrderBy(t => t.监测时间)
                            .Take(1000)
                            .ToList();
                    foreach (var item in items)
                    {
                        item.是否下发 = true;
                        item.QN = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        var port = CommonInformation.GetLetportById(item.设备信息ID);
                        if (string.IsNullOrEmpty(port?.工控机编号MN)) continue;
                        var result = "QN=" + item.QN + ";ST=32;CN=2011;PW=123456;MN=" + port.工控机编号MN + ";Flag=4;"
                                     + "CP=&&DataTime=" + item.监测时间.ToString("yyyyMMddHHmmss") + ";w00000-Rtd=" + item.RTD;
                        var cp = "";
                        var details = item.RealDataDetails;
                        Log.Info("details:" + details.Count);
                        foreach (var detail in details)
                        {
                            var factor = CommonInformation.GetFactorById(detail.污染物编码ID);
                            if (factor == null) continue;
                            cp += ";" + factor.污染物代码 + "-Rtd=" + detail.RTD;
                        }
                        result = result + cp + "&&";
                        result = Crc.WrapByCrc(result, "monitor");
                        Log.Info(result);
                        send_data data = new send_data
                        {
                            cn = "2011",
                            is_sent = false,
                            mn = port.工控机编号MN,
                            qn = item.QN,
                            send_string = result,
                            send_time = DateTime.Now,
                            sent_time = DateTime.Now
                        };
                        gCtx.send_data.Add(data);

                        gCtx.SaveChanges();
                    }
                    pCtx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        public static void Gen2051ToGateway()
        {
            try
            {
                using (GatewayMonitorContext gCtx = new GatewayMonitorContext())
                using (PlatformContext pCtx = new PlatformContext())
                {
                    var items =
                        pCtx.MinuteDataMains.Where(t => t.是否下发 == null || t.是否下发 == false)
                            .OrderBy(t => t.监测时间)
                            .Take(1000)
                            .ToList();
                    foreach (var item in items)
                    {
                        item.是否下发 = true;
                        item.QN = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        var port = CommonInformation.GetLetportById(item.设备信息ID);
                        if (string.IsNullOrEmpty(port?.工控机编号MN)) continue;
                        var result = "QN=" + item.QN + ";ST=32;CN=2051;PW=123456;MN=" + port.工控机编号MN + ";Flag=4;"
                                     + "CP=&&DataTime=" + item.监测时间.ToString("yyyyMMddHHmmss") + ";w00000-Cou=" + item.时段量;
                        var cp = "";
                        foreach (var detail in item.MinuteDataDetails)
                        {
                            var factor = CommonInformation.GetFactorById(detail.污染物编码ID);
                            if (factor == null) continue;
                            cp += ";" + factor.污染物代码 + "-Cou=" + detail.Cou;
                            cp += "," + factor.污染物代码 + "-Avg=" + detail.Avg;
                            cp += "," + factor.污染物代码 + "-Min=" + detail.Min;
                            cp += "," + factor.污染物代码 + "-Max=" + detail.Max;
                        }
                        result = result + cp + "&&";
                        result = Crc.WrapByCrc(result, "monitor");
                        Log.Info(result);
                        send_data data = new send_data
                        {
                            cn = "2051",
                            is_sent = false,
                            mn = port.工控机编号MN,
                            qn = item.QN,
                            send_string = result,
                            send_time = DateTime.Now,
                            sent_time = DateTime.Now
                        };
                        gCtx.send_data.Add(data);
                        gCtx.SaveChanges();
                    }
                    pCtx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        public static void Gen2061ToGateway()
        {
            try
            {
                double biaoXian = 0;
                using (GatewayMonitorContext gCtx = new GatewayMonitorContext())
                using (PlatformContext pCtx = new PlatformContext())
                {
                    var items =
                        pCtx.HourDataMains.Where(t => t.是否下发 == null || t.是否下发 == false)
                            .OrderBy(t => t.监测时间)
                            .Take(1000)
                            .ToList();
                    foreach (var item in items)
                    {
                        item.是否下发 = true;
                        ThreadUtil.Sleep(100);
                        item.QN = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        var port = CommonInformation.GetLetportById(item.设备信息ID);
                        if (string.IsNullOrEmpty(port?.工控机编号MN)) continue;
                        var result = "QN=" + item.QN + ";ST=32;CN=2061;PW=123456;MN=" + port.工控机编号MN + ";Flag=5;"
                                     + "CP=&&DataTime=" + item.监测时间.ToString("yyyyMMddHHmmss") + ";w00000-Cou=" + item.时段量;
                        var masterBegin = new DateTime(item.监测时间.Year, item.监测时间.Month, item.监测时间.Day);
                        var masterEnd = masterBegin.AddDays(1);
                        var masterDay = pCtx.DayDataMains
                            .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                            .Where(t => t.设备信息ID == port.ID)
                            .FirstOrDefault(t => t.监测时间 >= masterBegin && t.监测时间 < masterEnd);
                        if (masterDay?.时段量 != null)
                        {
                            result = result + ";w00000-Cou-Day=" + masterDay.时段量;
                        }
                        masterBegin = new DateTime(item.监测时间.Year, item.监测时间.Month, 1);
                        masterEnd = masterBegin.AddMonths(1);
                        var masterMonth = pCtx.MonthDataMains
                            .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                            .Where(t => t.设备信息ID == port.ID)
                            .FirstOrDefault(t => t.监测时间 >= masterBegin && t.监测时间 < masterEnd);
                        if (masterMonth?.时段量 != null)
                        {
                            result = result + ";w00000-Cou-Mon=" + masterMonth.时段量;
                        }
                        masterBegin = new DateTime(item.监测时间.Year, 1, 1);
                        masterEnd = masterBegin.AddYears(1);
                        var masterYear = pCtx.YearDataMains
                            .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                            .Where(t => t.设备信息ID == port.ID)
                            .FirstOrDefault(t => t.监测时间 >= masterBegin && t.监测时间 < masterEnd);
                        if (masterYear?.时段量 != null)
                        {
                            result = result + ";w00000-Cou-Yea=" + masterYear.时段量;
                        }

                        masterBegin = new DateTime(item.监测时间.Year, item.监测时间.Month, item.监测时间.Day);
                        masterEnd = masterBegin.AddDays(1);
                        //var masterAll = pCtx.DayDataMains
                        //    .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                        //    .Where(t => t.设备信息ID == port.ID)
                        //    .Where(t => t.监测时间 < masterEnd).Sum(t => t.时段量);
                        var masterAll =
                            pCtx.RealDataMonitorMains
                                .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                                .FirstOrDefault(t => t.设备信息ID == port.ID);
                        //.表显累计量;
                        if (masterAll != null)
                        {
                            result = result + ";w00000-Cou-Total=" + (masterAll.表显累计量 ?? 0);
                            biaoXian = masterAll.表显累计量 ?? 0;
                        }
                        var cp = "";
                        foreach (var detail in item.HourDataDetails)
                        {
                            var factor = CommonInformation.GetFactorById(detail.污染物编码ID);
                            if (factor == null) continue;
                            cp += ";" + factor.污染物代码 + "-Cou=" + detail.Cou;
                            cp += "," + factor.污染物代码 + "-Avg=" + detail.Avg;
                            cp += "," + factor.污染物代码 + "-Min=" + detail.Min;
                            cp += "," + factor.污染物代码 + "-Max=" + detail.Max;
                            var begin = new DateTime(item.监测时间.Year, item.监测时间.Month, item.监测时间.Day);
                            var end = begin.AddDays(1);
                            var day = pCtx.DayDataMains.Where(t => t.企业基本信息ID == port.企业基本信息ID)
                                .Where(t => t.设备信息ID == port.ID)
                                .Where(t => t.监测时间 >= begin && t.监测时间 < end)
                                .OrderByDescending(t => t.监测时间)
                                .FirstOrDefault();
                            var dayDetail = day?.DayDataDetails.FirstOrDefault(t => t.污染物编码ID == detail.污染物编码ID);
                            if (dayDetail != null)
                            {
                                cp += "," + factor.污染物代码 + "-Cou-Day=" + dayDetail.Cou;
                                cp += "," + factor.污染物代码 + "-Avg-Day=" + dayDetail.Avg;
                                cp += "," + factor.污染物代码 + "-Min-Day=" + dayDetail.Min;
                                cp += "," + factor.污染物代码 + "-Max-Day=" + dayDetail.Max;
                            }
                            begin = new DateTime(begin.Year, begin.Month, 1);
                            end = begin.AddMonths(1);
                            var month = pCtx.MonthDataMains.Where(t => t.企业基本信息ID == port.企业基本信息ID).Where(t => t.设备信息ID == port.ID).Where(t => t.监测时间 >= begin && t.监测时间 < end).OrderByDescending(t => t.监测时间).FirstOrDefault();
                            var monthDetail = month?.MonthDataDetails.FirstOrDefault(t => t.污染物编码ID == detail.污染物编码ID);
                            if (monthDetail != null)
                            {
                                cp += "," + factor.污染物代码 + "-Cou-Mon=" + monthDetail.Cou;
                                cp += "," + factor.污染物代码 + "-Avg-Mon=" + monthDetail.Avg;
                                cp += "," + factor.污染物代码 + "-Min-Mon=" + monthDetail.Min;
                                cp += "," + factor.污染物代码 + "-Max-Mon=" + monthDetail.Max;
                            }

                            begin = new DateTime(begin.Year, 1, 1);
                            end = begin.AddYears(1);
                            var year = pCtx.YearDataMains.Where(t => t.企业基本信息ID == port.企业基本信息ID).Where(t => t.设备信息ID == port.ID).Where(t => t.监测时间 >= begin && t.监测时间 < end).OrderByDescending(t => t.监测时间).FirstOrDefault();
                            var yearDetail = year?.YearDataDetails.FirstOrDefault(t => t.污染物编码ID == detail.污染物编码ID);
                            if (yearDetail != null)
                            {
                                cp += "," + factor.污染物代码 + "-Cou-Yea=" + yearDetail.Cou;
                                cp += "," + factor.污染物代码 + "-Avg-Yea=" + yearDetail.Avg;
                                cp += "," + factor.污染物代码 + "-Min-Yea=" + yearDetail.Min;
                                cp += "," + factor.污染物代码 + "-Max-Yea=" + yearDetail.Max;
                            }
                            masterEnd = DateTime.Now.AddDays(1);
                            var end1 = masterEnd;
                            var masterTotalIds = pCtx.DayDataMains
                                .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                                .Where(t => t.设备信息ID == port.ID)
                                .Where(t => t.监测时间 < end1).Select(t => t.ID);
                            var detailTotal =
                                pCtx.DayDataDetails.Where(t => masterTotalIds.Contains(t.主日数据ID))
                                    .Where(t => t.污染物编码ID == detail.污染物编码ID)
                                    .Sum(t => t.Cou);
                            if (detailTotal != null&& yearDetail!=null&& yearDetail.Avg.HasValue)
                            {
                                result = result + "," + factor.污染物代码 + "-Cou-Total=" + biaoXian * (yearDetail.Avg ?? 0)/1000;
                                //detailTotal;
                            }
                        }
                        result = result + cp + "&&";
                        result = Crc.WrapByCrc(result, "monitor");
                        Log.Info(result);
                        send_data data = new send_data
                        {
                            cn = "2061",
                            is_sent = false,
                            mn = port.工控机编号MN,
                            qn = item.QN,
                            send_string = result,
                            send_time = DateTime.Now,
                            sent_time = DateTime.Now
                        };
                        gCtx.send_data.Add(data);
                        gCtx.SaveChanges();
                    }
                    pCtx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
    }
}
